//
//  LocationManager.m
//  YueYueSpecailCarDriver
//
//  Created by 李亚军 on 17/2/24.
//  Copyright © 2017年 黄旺鑫. All rights reserved.
//

#import "LocationManager.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import "UserLocationModel.h"
#import "HeaderMacro.h"
#import "NotificationNameManager.h"


#import <Mapbox/Mapbox.h>
#import <Mapbox/MGLGeometry.h>
#import <MapboxGeocoder/MapboxGeocoder.swift-umbrella.h>

#import "MapManager.h"

#import <CoreLocation/CoreLocation.h>


@interface LocationManager ()<AMapLocationManagerDelegate , CLLocationManagerDelegate>



@end

static LocationManager *locationManager = nil;
@implementation LocationManager

+ (LocationManager *)shareManager {
    
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        
        locationManager = [[LocationManager alloc] init];
        
        if ([MapManager shareManager].currentMapType == MapTypeGD) {
            
            locationManager.amapLocationManager = [[AMapLocationManager alloc] init];
            locationManager.amapLocationManager.delegate = locationManager;
            locationManager.amapLocationManager.distanceFilter = 1; // 1米发起一次定位
            locationManager.amapLocationManager.locatingWithReGeocode = YES; // 返回逆地理信息
            if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0) {
                
                locationManager.amapLocationManager.allowsBackgroundLocationUpdates = YES;
            }
            
            [locationManager.amapLocationManager startUpdatingLocation]; // 开启持续定位
        }else if ([MapManager shareManager].currentMapType == MapTypeMapBox) {
            

            
            locationManager.mapBoxLocationManager = [[CLLocationManager alloc] init];
            locationManager.mapBoxLocationManager.delegate = locationManager;
            locationManager.mapBoxLocationManager.distanceFilter = 1;
            locationManager.mapBoxLocationManager.desiredAccuracy = 10;
            
            if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0) {
                
                locationManager.mapBoxLocationManager.allowsBackgroundLocationUpdates = YES;
            }
            
            [locationManager.mapBoxLocationManager startUpdatingLocation];
            [locationManager.mapBoxLocationManager startUpdatingHeading];
        }
        

        
    });
    
    return locationManager;
}

- (void)openLocationServiceSetting:(id)target {
    
    if ([CLLocationManager locationServicesEnabled] && ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined)) {
        
        
        
    }else if ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied) {
        
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"请开启定位功能" preferredStyle:(UIAlertControllerStyleAlert)];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication] canOpenURL:url]) {
                [[UIApplication sharedApplication] openURL:url];
                
            }
        }]];
        
        [target presentViewController:alertVC animated:YES completion:^{
            
        }];
        
        return;
    }

}


#pragma mark - AMapLocationManagerDelegate
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode
{
    
    
    if (self.userLocationModel == nil) {
        
        self.userLocationModel = [UserLocationModel new];
    }
    self.userLocationModel.userLocation = location;
    
    NSDictionary *locationDic = @{@"lat" : @(location.coordinate.latitude) , @"lng" : @(location.coordinate.longitude) , @"angle" : @(location.course)};
    [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_UserLocationChanged object:locationDic];
    
    self.userLocationModel.speed = location.speed;
    self.userLocationModel.altitude = location.altitude;
    
    if (reGeocode)
    {
        [self.userLocationModel setvalueWithAMapLocationReGeocode:reGeocode];
    }
}

- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error {
    
    self.userLocationModel = nil;
    [locationManager.amapLocationManager startUpdatingLocation]; // 开启持续定位
    [[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationName_GetUserLocationError" object:self.userLocationModel];
}

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation{
    
    if (self.userLocationModel == nil) {
        
        self.userLocationModel = [UserLocationModel new];
    }
    self.userLocationModel.userLocation = newLocation;
    
    NSDictionary *locationDic = @{@"lat" : @(newLocation.coordinate.latitude) , @"lng" : @(newLocation.coordinate.longitude) , @"angle" : @(newLocation.course)};
    [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_UserLocationChanged object:locationDic];
    
    self.userLocationModel.speed = newLocation.speed;
    self.userLocationModel.altitude = newLocation.altitude;
    
    
    return;
    
    MBReverseGeocodeOptions *options = [[MBReverseGeocodeOptions alloc] initWithCoordinate: CLLocationCoordinate2DMake(newLocation.coordinate.latitude, newLocation.coordinate.longitude)];
    
    MBGeocoder *geocoder = [MBGeocoder sharedGeocoder];
    __weak typeof(self) weakSelf = self;
    NSURLSessionDataTask *task = [geocoder geocodeWithOptions:options completionHandler:^(NSArray<MBGeocodedPlacemark *> * _Nullable placemarks,NSString * _Nullable attribution,NSError * _Nullable error) {
        
        __strong typeof(self) strongSelf = weakSelf;
        if (error == nil) {
            
            if (placemarks.count > 0) {
                
                MBGeocodedPlacemark * placemark = placemarks.firstObject;
                
                if (strongSelf.userLocationModel) {
                    
                    strongSelf.userLocationModel.userLocation = placemark.location;
                    
                    
                    NSLog(@"我是分割线---------------,这里是 mapbox 返回的信息");
                    
                    // 成名酱大骨头馆, 半屏山路1222-1224号, Xiamen Shi, Fujian, China
                    NSLog(@"%@",placemark.debugDescription);
                    
                    // 成名酱大骨头馆, 半屏山路1222-1224号, Xiamen Shi, Fujian, China
                    NSLog(@"%@" , placemark.qualifiedName);
                    strongSelf.userLocationModel.formattedAddress = placemark.qualifiedName == nil ? @"" : placemark.qualifiedName;
                    
                    // <+24.49474000,+118.19082000> +/- 0.00m (speed -1.00 mps / course -1.00) @ 2017/7/11 中国标准时间 下午3:22:49
                    NSLog(@"%@" , placemark.location);
                    
                    // (null)
                    NSLog(@"%@" , placemark.region);
                    
                    // 成名酱大骨头馆
                    NSLog(@"%@" , placemark.name);
                    
                    // (null)
                    NSLog(@"%@" , placemark.code);
                    strongSelf.userLocationModel.citycode = placemark.code == nil ? @"" : placemark.code;
                    strongSelf.userLocationModel.adcode = placemark.code == nil ? @"" : placemark.code;
                    
                    
                    // (null)
                    NSLog(@"%@" , placemark.wikidataItemIdentifier);
                    
                    // restaurant
                    NSLog(@"%@" , placemark.genres);
                    
                    // restaurant
                    NSLog(@"%@" , placemark.imageName);
                    
                    // <CNMutablePostalAddress: 0x174a8c210: street=半屏山路1222-1224号, subLocality=, city=Xiamen Shi, subAdministrativeArea=, state=Fujian, postalCode=, country=China, countryCode=CN>
                    NSLog(@"%@" , placemark.postalAddress);
                    
                    /**
                     {
                        ISOCountryCode = CN;
                        city = "Xiamen Shi";
                        country = China;
                        formattedAddressLines =     (
                            "\U534a\U5c4f\U5c71\U8def1222-1224\U53f7",
                            "Xiamen Shi",
                            Fujian,
                            China
                        );
                        name = "\U6210\U540d\U9171\U5927\U9aa8\U5934\U9986";
                        state = Fujian;
                        street = "\U534a\U5c4f\U5c71\U8def1222-1224\U53f7";
                        subAdministrativeArea = "Xiamen Shi";
                     }
                     */
                    NSLog(@"%@" , placemark.addressDictionary);
                    if (placemark.addressDictionary != nil && [placemark.addressDictionary isKindOfClass:[NSDictionary class]]) {
                        
                        
                        NSDictionary *addressDictionary = placemark.addressDictionary;
                        
                        if ([[addressDictionary allKeys] containsObject:@"country"]) {

                            strongSelf.userLocationModel.country = addressDictionary[@"country"] == nil ? @"" : addressDictionary[@"country"];
                        }else {
                            
                            strongSelf.userLocationModel.country = @"";
                        }
                        
                        if ([[addressDictionary allKeys] containsObject:@"state"]) {
                            
                            strongSelf.userLocationModel.province = addressDictionary[@"state"] == nil ? @"" : addressDictionary[@"state"];
                        }else {
                            
                            strongSelf.userLocationModel.province = @"";
                        }
                        
                        if ([[addressDictionary allKeys] containsObject:@""]) {
                            
                            strongSelf.userLocationModel.city = addressDictionary[@"city"] == nil ? @"" : addressDictionary[@"city"];
                        }else {
                            
                            strongSelf.userLocationModel.city = @"";
                        }
                        
                        self.userLocationModel.district = @"";
                        
                        if ([[addressDictionary allKeys] containsObject:@"street"]) {
                            
                            strongSelf.userLocationModel.street = addressDictionary[@"street"] == nil ? @"" : addressDictionary[@"street"];
                        }else {
                            
                            strongSelf.userLocationModel.street = @"";
                        }
                        
                        strongSelf.userLocationModel.number = @"";
                        
                        strongSelf.userLocationModel.POIName = placemark.name == nil ? @"" : placemark.name;
                        
                        strongSelf.userLocationModel.AOIName = @"";
                        
                        strongSelf.userLocationModel.altitude = placemark.location.altitude;
                        
                        strongSelf.userLocationModel.speed = placemark.location.speed;
                    }
                    
                    // 0592 295 1458
                    NSLog(@"%@" , placemark.phoneNumber);
                    
                }
            }
        }

//        MBPlacemark *placemark = placemarks[0];
//        NSLog(@"%@", placemark.imageName);
//        // telephone
//        NSLog(@"%@", [placemark.genres componentsJoinedByString:@", "]);
//        // computer, electronic
//        NSLog(@"%@", placemark.administrativeRegion.name);
//        // New York
//        NSLog(@"%@", placemark.administrativeRegion.code);
//        // US-NY
//        NSLog(@"%@", placemark.place.wikidataItemIdentifier);
//        // Q60
    }];
    [task resume];
}

- (void)locationManager:(CLLocationManager *)manager
       didUpdateHeading:(CLHeading *)newHeading {
    
    
}

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error {
    
    self.userLocationModel = nil;
    [locationManager.mapBoxLocationManager startUpdatingLocation]; // 开启持续定位
    [[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationName_GetUserLocationError" object:self.userLocationModel];
}


#pragma mark - setter
/// 这里设置的是高德地图的 key, 由于 mapbox 的 key 在 info.plist 文件中,所以不需要刻意的设置
- (void)setMapAPIKey:(NSString *)mapAPIKey {
    
    _mapAPIKey = mapAPIKey;
    [AMapServices sharedServices].apiKey = mapAPIKey;
    [_amapLocationManager startUpdatingLocation];
}

@end
